require('babel-core/register')()
require('babel-polyfill')
const Koa = require('koa')
const KoaCors = require('koa-cors')
const koaStatic = require('koa-static')
const bodyParser = require('koa-bodyparser')
const koaBody = require('koa-body')
const path = require('path')
const adminsRoute = require('./routes/admins')
const moviesRoute = require('./routes/movies')
const crawlerRoute = require('./routes/crawler')
// const staticRoute = require('./routes/static')
// const mongoose = require('mongoose')

const { connect, initSchemas, initAdmin } = require('./database/init')

    ; (async () => {
        await connect()

        initSchemas()

        await initAdmin()

        // require('./common/tasks/movie')
        // require('./common/tasks/api')
        // require('./common/tasks/trailer')
        // require('./common/tasks/qiniu')
        // const Movie = mongoose.model('Movie')

        // const movies = await Movie.find({})

        // console.log(111, movies)
    })()

const app = new Koa()

app.use(koaBody({ multipart: true }))

app.use(bodyParser())

app.use(async (ctx, next) => {
    try {
        console.log(`request with path ${ctx.path}`)
        await next()
    } catch (err) {
        console.log('server', err)
        ctx.status = 500
        ctx.body = 'please try again later'
    }
})

app.use(KoaCors())

app.use(koaStatic(path.join(__dirname, './')))

// routes
app.use(adminsRoute.routes(), adminsRoute.allowedMethods())
app.use(moviesRoute.routes(), moviesRoute.allowedMethods())
app.use(crawlerRoute.routes(), crawlerRoute.allowedMethods())
// app.use(staticRoute.routes(), staticRoute.allowedMethods())

const HOST = process.env.HOST || '0.0.0.0'
const PORT = process.env.PORT || 3000

app.listen(PORT, HOST, () => {
    console.log(`server is listening on ${HOST}:${PORT}`)
})
